﻿using Common;
using Network.UpdateData;
using SFJDManagement.SocketHandle;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace SFJDManagement
{
    /// <summary>
    /// Page_Register.xaml 的交互逻辑
    /// </summary>
    public partial class Page_Register : Page
    {
        private ClassBrigade brigade = null;
        public ClassContact contact = new ClassContact();
        public List<ClassVehicle> vehicles = new List<ClassVehicle>();
        public Win_Brigade cBrigade;
        public static Page_Register instance;

        private Brush but_BorderColorDefault = null;
        private bool isInputErro = false;

        public Page_Register()
        {
            InitializeComponent();
            instance = this;
            Ini();
        }

        public Page_Register(ClassData classData)
        {
            InitializeComponent();
            instance = this;
            Ini();
            TypeInData(classData);
        }

        /// <summary>
        /// 如果Temp.xml保存有Temp或Cache数据则跳到错误页面，且自动填入保存的数据
        /// </summary>
        /// <param name="data"></param>
        private void TypeInData(ClassData data)
        {
            List<ClassBrigade> list_Bri = Runtime.xmlBrigade.GetAll();
            foreach(ClassBrigade bri in list_Bri)
            {
                if(bri.Guid == data.Brigade)
                {
                    brigade = bri;
                    but_Brigade.Content = bri.FullName;
                }
            }
            DPHappenDate.Text = data.TimeHappen.Date.ToString();
            DPHappenHour.Text = data.TimeHappen.Hour.ToString();
            DPHappenMin.Text = data.TimeHappen.Minute.ToString();
            DPEntrust.Text = data.TimeEntrust.Date.ToString();
            tbContactName.Text = data.Contact;
            comboBox.SelectedIndex = data.CaseType;
            DGVechicles.ItemsSource = data.Vehicles;
            vehicles = data.Vehicles;
        }

        private void Ini()
        {
            DGVechicles.ItemsSource = vehicles;
            but_BorderColorDefault = but_Brigade.BorderBrush;
            DPHappenDate.DisplayDateEnd = DateTime.Now;
            DPEntrust.DisplayDateEnd = DateTime.Now;
            comboBox.ItemsSource = Enum.GetNames(typeof(EnumCaseType));
        }

        private void but_Register_Click(object sender, RoutedEventArgs e)
        {
            if (checkInput())
            {
                return;
            }
            try
            {
                but_Register.IsEnabled = false;
                ClassData dat = new ClassData();
                string happen0 = DPHappenDate.Text + " " + DPHappenHour.Text + ":" + DPHappenMin.Text;
                DateTime happen = Convert.ToDateTime(happen0);
                DateTime entrust = Convert.ToDateTime(DPEntrust.Text);
                string happ = happen.ToString("yyyyMMdd");
                dat.ID = 0;
                dat.Code = brigade.Code + happ.Replace(" ", "");
                dat.CaseType = comboBox.SelectedIndex;
                dat.Brigade = brigade.Guid;
                dat.Contact = contact.Name;
                dat.User = Runtime.config.UserGuid;
                dat.TimeHappen = happen;
                dat.TimeEntrust = entrust;
                dat.TimeArrange = DateTime.Now;
                foreach (ClassVehicle vehicle in vehicles)
                {
                    if (vehicle != null)
                    {
                        if (vehicle.Number != null & vehicle.Brand != null & vehicle.Type != null)
                        {
                            if (vehicle.Number != "" & vehicle.Brand != "" & vehicle.Type != "")
                            {
                                dat.Vehicles.Add(vehicle);
                            }
                        }
                    }
                }
                Runtime.xmlTemp.AddDataCache(dat);
                Packet packet = new Packet(typeof(SC01RegisterDataReply).GetClient2ServerKey(), Runtime.config.UserGuid, dat.CodingToString());
                CSendMsg.SendMsgWait(packet.ToBytes());

                //new CSendMsg().SendMsgWait("2001" + dat.CodingToString());
            }
            catch
            {
                but_Register.IsEnabled = true;
                //Log.ToConsole("数据有错误！！" + "  " + ex.Message);
            }
        }

        /// <summary>
		/// 检查用户输入的内容
		/// </summary>
		public bool checkInput()
        {
            isInputErro = false;   //重置变量
                                        //检查委托人
            if (brigade == null | but_Brigade.Content == null || but_Brigade.Content.ToString() == "选择委托人")
                InputErro(but_Brigade);
            else
                InputNoErro(but_Brigade);
            //检查发生日期
            if (DPHappenDate.Text == "")
                InputErro(DPHappenDate);
            else
                InputNoErro(DPHappenDate);
            //检查发生小时
            if (DPHappenHour.Text == null || DPHappenHour.Text == "")
                InputErro(DPHappenHour);
            else
                InputNoErro(DPHappenHour);
            //检查发生分钟
            if (DPHappenMin.Text == null || DPHappenMin.Text == "")
                InputErro(DPHappenMin);
            else
                InputNoErro(DPHappenMin);
            //检查委托时间
            if (DPEntrust.Text == "")
                InputErro(DPEntrust);
            else
                InputNoErro(DPEntrust);
            //检查联系人名字
            if (tbContactName.Text == null || tbContactName.Text == "" || !Regex.IsMatch(tbContactName.Text, "^[\u4E00-\u9FA5]|[9FA6-9FCB]|[3400-4DB5]|[20000-2A6D6]|[2A700-2B734]|[2B740-2B81D]{2,}$"))
                InputErro(tbContactName);
            else
                InputNoErro(tbContactName);
            //检查联系人电话
            //if (brigade != null && brigade.Code != "ZZSFJD" && tbContactPhone.Text == "")
            //    InputErro(tbContactPhone);
            //else if (tbContactPhone.Text != "" && !Regex.IsMatch(tbContactPhone.Text, @"^1[0-9]{10}$"))
            //    InputErro(tbContactPhone);
            //else
            //    InputNoErro(tbContactPhone);
            //检查事故类型
            if (comboBox.SelectedValue == null)
                InputErro(comboBox);
            else
                InputNoErro(comboBox);
            //检查是否输入了车辆号牌、品牌、型号
            if (vehicles.Count == 0)
            {
                InputErro(DGVechicles);
            }
            else
            {
                for (int i = vehicles.Count - 1; i >= 0; i--)  //删除空行，但是最后还有一行空行
                {
                    if ((vehicles[i].Number == null | vehicles[i].Number == string.Empty) & 
                        (vehicles[i].Brand == null | vehicles[i].Brand == string.Empty) & 
                        (vehicles[i].Type == null | vehicles[i].Type == string.Empty))
                        vehicles.RemoveAt(i);
                    DGVechicles.Items.Refresh();
                }
                for (int i = vehicles.Count - 1; i >= 0; i--)  //从倒数第二行向前检查
                {
                    for (int j = 2; j >= 0; j--)
                    {
                        DataGridCell cell = DataGridDevelop.GetCell(DGVechicles, i, j);
                        if (cell.Content.GetType().Equals(typeof(TextBlock)))
                        {
                            TextBlock tb = cell.Content as TextBlock;
                            if (tb.Text == null || tb.Text == "")
                                InputErro(cell);
                            else
                                InputNoErro(cell);
                            if(j == 2 && Regex.IsMatch(tb.Text, "^.*无|未知|不.*$"))
                            {
                                InputErro(cell);
                            }
                            else
                            {
                                InputNoErro(cell);
                            }
                        }
                    }
                }
                bool isChecked = false;
                foreach (ClassVehicle veh in vehicles) //检查是否勾选鉴定项目
                {
                    if (veh.Procj | veh.Procs | veh.Procy | veh.Profx | veh.Progc | veh.Prohj | veh.Projsy | veh.Pross | veh.Prosx)
                        isChecked = true;
                }
                if (isChecked)
                    InputNoErro(DGVechicles);
                else
                    InputErro(DGVechicles);
            }
            return isInputErro;
        }

        public void SetBrigade(ClassBrigade newBrigade)
        {
            brigade = newBrigade;
            but_Brigade.Content = brigade.FullName;
        }

        /// <summary>
		/// 如果控件有错误，则把控件边框变为红色
		/// </summary>
		/// <param name="cc"></param>
		private void InputErro(Control cc)
        {
            cc.BorderBrush = Brushes.Red;
            isInputErro = true;
        }

        /// <summary>
        /// 如果控件没有错误，则控件边框不变；如果是修改后的结果，则把边框变为黑色
        /// </summary>
        /// <param name="cc"></param>
        private void InputNoErro(Control cc)
        {
            if (cc.BorderBrush == Brushes.Red)
            {
                cc.BorderBrush = but_BorderColorDefault;
            }
        }

        /// <summary>
		/// 清空输入的数据, 委托处理
		/// </summary>
        public void resetData()
        {
            Dispatcher.Invoke(new Action(delegate {
                but_Brigade.Content = null;
                DPHappenDate.Text = null;
                DPHappenHour.Clear();
                DPHappenMin.Clear();
                DPEntrust.Text = null;
                tbContactName.Clear();
                tbContactPhone.Clear();
                comboBox.SelectedIndex = -1;
                vehicles = new List<ClassVehicle>();
                DGVechicles.ItemsSource = null;
                DGVechicles.ItemsSource = vehicles;
                brigade = new ClassBrigade();
                contact = new ClassContact();
                but_Register.IsEnabled = true;
            }));
            //Dispatcher.InvokeShutdown();
            if (!Runtime.xmlTemp.IsEmpty())
            {
                Dispatcher.Invoke(new Action(delegate
                {
                    Win_Main2.instance.Layout_Function.Content = new Page_DataErr();
                }));
            }
        }

        private void tbContactName_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (tbContactName.Text == null)
                return;
            contact.Name = tbContactName.Text;
            contact.Phone = Runtime.xmlContact.GetContact(brigade.Guid, contact.Name);
            if (contact.Phone != null)
            {
                tbContactPhone.Text = contact.Phone;
            }
            else
            {
                tbContactPhone.Text = null;
            }
        }

        private void tbContactPhone_LostFocus(object sender, RoutedEventArgs e)
        {
            if(brigade == null)
            {
                return;
            }
            ClassContact con = Runtime.xmlContact.GetContactByPhone(brigade.Guid.ToString(), tbContactPhone.Text);
            if (con != null)
            {
                tbContactName.Text = con.Name;
                contact = con;
            }
            else
            {
                if (tbContactPhone.Text != null && tbContactName.Text != null && brigade.Guid != null)
                {
                    if (tbContactPhone.Text != "" && tbContactName.Text != "")
                    {
                        contact.Brigade = brigade.Guid;
                        contact.Phone = tbContactPhone.Text;
                        Runtime.xmlContact.AddContact(contact);
                        Packet packet = new Packet(typeof(SC03RegisterContact).GetClient2ServerKey(), Runtime.config.UserGuid, contact.Coding2String());
                        CSendMsg.SendMsgNoWait(packet.ToBytes());
                    }
                }
            }
        }

        private void DPHappenHour_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (DPHappenHour.Text == null || DPHappenHour.Text == "")
            {
                DPHappenHour.Text = "0";
            }
            int t = int.Parse(DPHappenHour.Text);
            if (e.Delta > 0)
            {
                t++;
                DPHappenHour.Text = t.ToString();
            }
            else
            {
                t--;
                DPHappenHour.Text = t.ToString();
            }
        }

        private void DPHappenHour_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                int t = int.Parse(DPHappenHour.Text);
                if (t > 23)
                {
                    DPHappenHour.Text = "0";
                }
                else if (t < 0)
                {
                    DPHappenHour.Text = "23";
                }
            }
            catch
            {
                DPHappenHour.Clear();
            }
        }

        private void DPHappenMin_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                int t = int.Parse(DPHappenMin.Text);
                if (t > 59)
                {
                    DPHappenMin.Text = "0";
                }
                else if (t < 0)
                {
                    DPHappenMin.Text = "59";
                }
            }
            catch
            {
                DPHappenMin.Clear();
            }
        }

        private void DPHappenMin_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (DPHappenMin.Text == null || DPHappenMin.Text == "")
            {
                DPHappenMin.Text = "0";
            }
            int t = int.Parse(DPHappenMin.Text);
            if (e.Delta > 0)
            {
                t++;
                DPHappenMin.Text = t.ToString();
            }
            else
            {
                t--;
                DPHappenMin.Text = t.ToString();
            }
        }

        private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboBox.SelectedValue == null)
                return;
            if (comboBox.SelectedValue.ToString() == "车损鉴定")
            {
                DGVechicles.Columns[3].Visibility = Visibility.Hidden;
                DGVechicles.Columns[4].Visibility = Visibility.Hidden;
                DGVechicles.Columns[5].Visibility = Visibility.Hidden;
                DGVechicles.Columns[6].Visibility = Visibility.Visible;
                DGVechicles.Columns[7].Visibility = Visibility.Hidden;
                DGVechicles.Columns[8].Visibility = Visibility.Hidden;
                DGVechicles.Columns[9].Visibility = Visibility.Hidden;
                DGVechicles.Columns[10].Visibility = Visibility.Hidden;
                DGVechicles.Columns[11].Visibility = Visibility.Hidden;
            }
            else
            {
                DGVechicles.Columns[3].Visibility = Visibility.Visible;
                DGVechicles.Columns[4].Visibility = Visibility.Visible;
                DGVechicles.Columns[5].Visibility = Visibility.Visible;
                DGVechicles.Columns[6].Visibility = Visibility.Hidden;
                DGVechicles.Columns[7].Visibility = Visibility.Visible;
                DGVechicles.Columns[8].Visibility = Visibility.Visible;
                DGVechicles.Columns[9].Visibility = Visibility.Visible;
                DGVechicles.Columns[10].Visibility = Visibility.Visible;
                DGVechicles.Columns[11].Visibility = Visibility.Visible;
            }
        }

        private void but_Brigade_Click(object sender, RoutedEventArgs e)
        {
            cBrigade = new Win_Brigade(this);
            cBrigade.Owner = Win_Main2.instance;
            //cBrigade.Visibility = Visibility.Visible;
            //Visibility = Visibility.Hidden;
        }

        private void DPHappenDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (DPHappenDate.DisplayDate != null && DPEntrust.Text == "")
            {
                DPEntrust.DisplayDateStart = DPHappenDate.SelectedDate;
            }
        }
    }
}
